package com.jifeng.sterilizer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jifeng.sterilizer.constant.WXUrlConstant;
import com.jifeng.sterilizer.entity.*;
import com.jifeng.sterilizer.service.*;
import com.jifeng.sterilizer.usercount.MyHttpSessionListener;
import com.jifeng.sterilizer.utils.HttpUtils;
import com.jifeng.sterilizer.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

@Service("homeService")
@Slf4j
public class HomeServiceImpl implements HomeService {

    @Autowired
    UserService userService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    UserDeviceService userDeviceService;

    @Autowired
    UserControllerService userControllerService;

    @Autowired
    ControllerService controllerService;

    @Autowired
    LiquidService liquidService;

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    @Override
    public R getListUserDevices(Map<String, Object> params) {
        try {
            HttpServletRequest request = getRequest();
            String requestURI = request.getRequestURI();
            Integer uid = Integer.valueOf(String.valueOf(params.get("userId")));
            if (requestURI.equals(WXUrlConstant.WX_LIST_USER_DEVICES)) {
                Map userInfo = HttpUtils.getTokenInfo(request);
                Object tokenId = userInfo.get("id");
                if (!tokenId.equals(uid)) {
                    log.warn("方法：{}，错误信息：{}", "获取用户绑定的消毒机信息", "只能查询本用户的数据");
                    return R.error(400, "只能查询本用户的数据");
                }
            }

            List<Map<String, Object>> mapList = new ArrayList<>();
            List<UserDeviceEntity> userDeviceEntityList = userDeviceService.list(new QueryWrapper<UserDeviceEntity>().eq("user_id", uid));
            if (userDeviceEntityList.isEmpty()) {
                log.warn("方法：{}，错误信息：{}", "获取用户绑定的消毒机信息", "无效的用户id");
                return R.ok().put("data", mapList);
            }
            userDeviceEntityList.forEach(userDeviceEntity -> {
                Map<String, Object> map = new HashMap<>();
                Long deviceNumber = userDeviceEntity.getDeviceNumber();
                if (deviceNumber == null) {
                    log.warn("方法：{}，错误信息：{}", "获取用户绑定的消毒机信息", "用户绑定的消毒机编号为空");
                    return;
                }
                DeviceEntity deviceEntity = deviceService.getOne(new QueryWrapper<DeviceEntity>().eq("number", deviceNumber), false);
                if (deviceEntity == null) {
                    log.warn("方法：{}，错误信息：{}", "获取用户绑定的消毒机信息", "消毒机无效");
                    return;
                }
                String name = deviceEntity.getName();
                Long id = deviceEntity.getId();
                map.put("id", id);
                map.put("number", deviceNumber);
                map.put("name", name);
                mapList.add(map);
            });
            return R.ok().put("data", mapList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取用户绑定的消毒机信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

    /*
     {code:"200",msg:"成功",data{
     drug: {total: '', buy: '', use: ''},
     control: {total: '', online: ''},
     sterilizer: {total: '', online: ''},
     user: {total: '', online: ''}}}
     */
    @Override
    public R pcGetHomeInfo() {
        try {
            Map<String, Object> rsMap = new HashMap<>();
            Map<String, Object> drugMap = new HashMap<>();
            Map<String, Object> controllerMap = new HashMap<>();
            Map<String, Object> sterilizerMap = new HashMap<>();
            Map<String, Object> userMap = new HashMap<>();

            List<LiquidEntity> liquidEntityList = liquidService.list();
//            if (liquidEntityList==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无有效药剂");
//                return R.error(400, "无有效药剂");
//            }
            List<LiquidEntity> liquidEntityList2 = liquidService.list(new QueryWrapper<LiquidEntity>().eq("status", 0));
//            if (liquidEntityList2==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无已注册药剂");
//                return R.error(400, "无已注册药剂");
//            }
            List<LiquidEntity> liquidEntityList3 = liquidService.list(new QueryWrapper<LiquidEntity>().eq("status", 2));
//            if (liquidEntityList3==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无已使用药剂");
//                return R.error(400, "无已使用药剂");
//            }
            int liquidTotal = liquidEntityList.size();
            int buy = liquidEntityList2.size();
            int use = liquidEntityList3.size();
            drugMap.put("total", liquidTotal);
            drugMap.put("buy", buy);
            drugMap.put("use", use);

            List<ControllerEntity> controllerEntityList = controllerService.list();
//            if (controllerEntityList==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无有效中控器");
//                return R.error(400, "无有效中控器");
//            }
            List<ControllerEntity> controllerEntityList2 = controllerService.list(new QueryWrapper<ControllerEntity>()
                    .eq("status", 0));
//            if (controllerEntityList2==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无状态为0的中控器");
//                return R.error(400, "无状态为0的中控器");
//            }
            int controllerTotal = controllerEntityList.size();
            int controllerOnline = controllerEntityList2.size();
            controllerMap.put("total", controllerTotal);
            controllerMap.put("online", controllerOnline);

            List<DeviceEntity> deviceEntityList = deviceService.list();
//            if (deviceEntityList==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无有效消毒机");
//                return R.error(400, "无有效消毒机");
//            }
            List<DeviceEntity> deviceEntityList2 = deviceService.list(new QueryWrapper<DeviceEntity>().eq("status", 0));
//            if (deviceEntityList2==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无状态为0消毒机");
//                return R.error(400, "无状态为0消毒机");
//            }
            int deviceTotal = deviceEntityList.size();
            int deviceOnline = deviceEntityList2.size();
            sterilizerMap.put("total", deviceTotal);
            sterilizerMap.put("online", deviceOnline);

            List<UserEntity> userEntityList = userService.list(new QueryWrapper<UserEntity>().eq("type", 4).eq("status", 2));
//            if (userEntityList==null){
//                log.warn("方法：{}，错误信息：{}", "后台首页", "无审核通过的手机用户");
//                return R.error(400, "无状态为0消毒机");
//            }
            int userTotal = userEntityList.size();
            int userOnline = MyHttpSessionListener.online;
            userMap.put("total", userTotal);
            userMap.put("online", userOnline);

            rsMap.put("drug", drugMap);
            rsMap.put("control", controllerMap);
            rsMap.put("user", userMap);
            rsMap.put("sterilizer", sterilizerMap);
            return R.ok().put("data", rsMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "后台首页", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }
}
